﻿
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace EmoneyWeiXinCommon
{
    public class OAuth2Helper
    {
        #region 通过微信鉴权跳转连接（可获得Code）
        /// <summary>
        /// 通过微信鉴权跳转连接（可获得Code）
        /// </summary>
        /// <param name="redirectUri"></param>
        /// <returns></returns>
        public static string GetAuthorizeUrl(string redirectUri, string appid)
        {
            return GetAuthorizeUrl(redirectUri, true, appid);
        }
        public static string GetAuthorizeUrl(string redirectUri, bool isbasic, string appid)
        {
            Dictionary<string, string> urlParams = new Dictionary<string, string>();
            urlParams.Add("appid", appid.Trim());
            urlParams.Add("redirect_uri", System.Web.HttpUtility.UrlEncode(redirectUri).Trim());
            urlParams.Add("response_type", "code");
            urlParams.Add("scope", isbasic ? "snsapi_base" : "snsapi_userinfo");
            urlParams.Add("state", "state");
            string url = Config.WeiXin_OAuth2_ApiUrl + "?";
            foreach (string key in urlParams.Keys)
            {
                url += key + "=" + urlParams[key] + "&";
            }
            return url.TrimEnd('&') + "#wechat_redirect";
        }
        #endregion

        /// <summary>
        /// 根据access_token，openId，获取用户的详细信息
        /// </summary>
        /// <param name="access_token"></param>
        /// <param name="openId"></param>
        /// <returns></returns>
        public static WeiXinUserInfo GetwxUserInfo(string access_token, string openId)
        {
            string url = Config.getWxUserInfoApiUrl;
            Dictionary<string, string> paras = new Dictionary<string, string>();
            paras.Add("access_token", access_token);
            paras.Add("openid", openId);
            paras.Add("lang", "zh_TW");
            string json = NetHelper.LoadData(url, paras);
            return JsonTools.ToObject<WeiXinUserInfo>(json);
        }


        [Serializable]
        public class WeiXinUserInfo
        {
            public string openid { get; set; }
            public string nickname { get; set; }
            public int sex { get; set; }
            public string province { get; set; }
            public string city { get; set; }
            public string country { get; set; }
            public string headimgurl { get; set; }

        }

    }
}
